package com.java.socket.tcp.multiclient.multithread.server;

import java.io.*;
import java.net.Socket;

/**
 * 多客户端Socket情况下的服务端Socket线程类
 * <p>使用多线程的方式</p>
 *
 * @author xzmeasy
 * @version 1.0
 * @since 星期一 十二月,2018
 */
@SuppressWarnings("Duplicates")
public class ServerSocketThread extends Thread {

    private Socket socket;

    public  ServerSocketThread() {}

    public ServerSocketThread(Socket socket) {
        this.socket = socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 从Socket创建输入流，用于读取客户端发送的消息
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String temp = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((temp = bufferedReader.readLine()) != null) {
                stringBuilder.append(temp);
            }
            System.out.println("从客户端接收到的消息：" + stringBuilder.toString());


            // 从Socket创建输出流，用于反馈客户端发送的消息
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            String message = "服务端反馈的消息";
            printWriter.write(message);
            printWriter.flush();


            // 关闭资源
            printWriter.close();
            outputStream.close();
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
